//
//  UIViewController+BaseVC.m
//  ImGuider
//
//  Created by 李陆涛 on 2017/12/11.
//  Copyright © 2017年 imguider. All rights reserved.
//

#import "UIViewController+BaseVC.h"
#import <UMSocialCore/UMSocialCore.h>

#import <objc/runtime.h>
#import "CustomNavBar.h"

static NSString *barBGAlphaKey = @"barBGAlphaKey";
static NSString *customBarStyleKey = @"customBarStyleKey";
static NSString *isHiddenPlayStatusButtonKey = @"isHiddenPlayStatusButtonKey";

typedef NS_ENUM(NSUInteger, BaseVCViewTag) {
    BaseVCViewTagThemeImagView = 10086,
    BaseVCViewTagBlackbgView,
    BaseVCViewTagBLineView
};

@interface UIViewController ()


@end

@implementation UIViewController (BaseVC)


+ (void)load {
    [super load];

    Method fromMethod = class_getInstanceMethod([self class], @selector(rt_navigationBarClass));
    Method toMethod = class_getInstanceMethod([self class], @selector(swizzling_navigationBarClass));

    if (!class_addMethod([self class], @selector(viewDidLoad), method_getImplementation(toMethod), method_getTypeEncoding(toMethod))) {
        method_exchangeImplementations(fromMethod, toMethod);
    }
}

- (Class)swizzling_navigationBarClass {
    
    return [CustomNavBar class];
}

//- (void)swizzlingViewDidAppear:(BOOL)animated {
//    
//    UIView *background = self.navigationController.navigationBar.subviews.firstObject;
//    
//    if (background) {
//        
//        if (![background.subviews containsObject:self.barbgView]) {
//            [self.navigationController.navigationBar.subviews.firstObject addSubview:self.barbgView];
//            
//            NSLog(@"-----------加上了 %@",self.class);
//        }
//    }
//    [self swizzlingViewDidAppear:animated];
//}

- (void)setupNav {
    
    self.rt_navigationController.transferNavigationBarAttributes = YES;
    
    if (self.customBarStyle == UIStatusBarStyleLightContent) {
        [self setNavTitleWithColor:[UIColor whiteColor]];
    } else {
        [self setNavTitleWithColor:[UIColor blackColor]];
    }
}

- (void)setNavTitleWithColor:(UIColor *)color {
    
    self.navigationController.navigationBar.tintColor = color;
    
    NSMutableDictionary *dict=[NSMutableDictionary dictionary];
    [dict setObject:color forKey:NSForegroundColorAttributeName];
    [dict setObject:FontBold(18) forKey:NSFontAttributeName];
    
    self.navigationController.navigationBar.titleTextAttributes = dict;
}

- (void)setNavBlackGradient {
    
    CustomNavBar *barbgView = (CustomNavBar *)self.navigationController.navigationBar;
    
    [barbgView setNavBlackGradient];
    
    self.customBarStyle = UIStatusBarStyleLightContent;
}

- (void)setNavThemeGradient {
    
    CustomNavBar *barbgView = (CustomNavBar *)self.navigationController.navigationBar;

    [barbgView setNavThemeGradient];
    
    self.customBarStyle = UIStatusBarStyleLightContent;
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    
    return self.customBarStyle;
}

- (void)closeAutomaticallyAdjustsScrollViewInsets:(UIScrollView *)scrollerView {
    
    // ios 11  scrollvew 的位置调整
    if (@available(iOS 11.0, *)) {
        scrollerView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
}

- (UIBarButtonItem *)rt_customBackItemWithTarget:(id)target action:(SEL)action {
    
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back"] style:UIBarButtonItemStylePlain target:target action:action];
    return item;
}


- (void)rightBarButton:(NSString *)title color:(UIColor *)color selector:(SEL)selector {
    
    [self barItemWithNameArray:@[title] colorArray:color ? @[color] : nil selArray:@[NSStringFromSelector(selector)] isLeft:NO];
}

- (void)rightBarButtonWithImageName:(NSString *)imageName selector:(SEL)selector {
    
    [self barItemWithImageNameArray:@[imageName] selArray:@[NSStringFromSelector(selector)] isLeft:NO];
}


- (void)barItemWithNameArray:(NSArray <NSString *>* _Nonnull)nameArray colorArray:(NSArray <UIColor *>* _Nullable)colorArray selArray:(NSArray <NSString *>* _Nonnull)selNameArray isLeft:(BOOL)isLeft {
    
    NSMutableArray *barItemArray = [NSMutableArray array];
    
    for (int i = 0; i < nameArray.count; i ++) {
        
        NSString *title = nameArray[i];
        UIColor *color = [UIColor whiteColor];
        
        if (colorArray.count > i) {
            color = colorArray[i];
        }
        SEL selector = NSSelectorFromString(selNameArray[i]);
        
        UIBarButtonItem *barItem = [[UIBarButtonItem alloc] initWithTitle:title style:UIBarButtonItemStylePlain target:self action:selector];
        barItem.tintColor = color;
        
        [barItemArray addObject:barItem];
    }
    
    if (isLeft) {
        self.navigationItem.leftBarButtonItems = barItemArray;
    } else {
        
        if (!self.isHiddenPlayStatusButton) {
            
            UIBarButtonItem *space = [[UIBarButtonItem alloc] initWithTitle:@"    " style:UIBarButtonItemStylePlain target:nil action:nil];
            
            [barItemArray insertObject:space atIndex:0];
        }
        
        self.navigationItem.rightBarButtonItems = barItemArray;
    }
}

- (void)barItemWithImageNameArray:(NSArray <NSString *>* _Nonnull)imageNameArray selArray:(NSArray <NSString *>* _Nonnull)selNameArray isLeft:(BOOL)isLeft {
    
    NSMutableArray *barItemArray = [NSMutableArray array];
    
    for (int i = 0; i < imageNameArray.count; i ++) {
        
        UIImage *image = [UIImage imageNamed:imageNameArray[i]];
        
        SEL selector = NSSelectorFromString(selNameArray[i]);
        
        UIBarButtonItem *barItem = [[UIBarButtonItem alloc] initWithImage:image style:UIBarButtonItemStylePlain target:self action:selector];
        
        [barItemArray addObject:barItem];
        
        if (isLeft && i != 0) {
            
            barItem.imageInsets = UIEdgeInsetsMake(0, -10, 0, 10);
        }
        
    }
    
    if (isLeft) {
        
        self.navigationItem.leftBarButtonItems = barItemArray;
        self.rt_disableInteractivePop = NO;
    } else {
        
        if (!self.isHiddenPlayStatusButton) {
            
            UIBarButtonItem *space = [[UIBarButtonItem alloc] initWithTitle:@"    " style:UIBarButtonItemStylePlain target:nil action:nil];
            
            [barItemArray insertObject:space atIndex:0];
        }
        
        self.navigationItem.rightBarButtonItems = barItemArray;
    }
}

- (void)setCustomBarStyle:(UIStatusBarStyle)customBarStyle {
    
    objc_setAssociatedObject(self, &customBarStyleKey, @(customBarStyle), OBJC_ASSOCIATION_COPY_NONATOMIC);
    
    if (customBarStyle == UIStatusBarStyleLightContent) {
        [self setNavTitleWithColor:[UIColor whiteColor]];
    } else {
        [self setNavTitleWithColor:[UIColor blackColor]];
    }
    
    [self setNeedsStatusBarAppearanceUpdate];
}

- (UIStatusBarStyle)customBarStyle {
    
    return [objc_getAssociatedObject(self, &customBarStyleKey) integerValue];
}

//- (void)setBarbgView:(UIView *)barbgView {
//
//    objc_setAssociatedObject(self, &barbgViewKey, barbgView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
//}
//
//- (UIView *)barbgView{
//
//    return objc_getAssociatedObject(self, &barbgViewKey);
//}

- (void)setIsHiddenPlayStatusButton:(BOOL)isHiddenPlayStatusButton {
    
    objc_setAssociatedObject(self, &isHiddenPlayStatusButtonKey, @(isHiddenPlayStatusButton), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (BOOL)isHiddenPlayStatusButton {
    
    return [objc_getAssociatedObject(self, &isHiddenPlayStatusButtonKey) boolValue];
}


- (void)setBarBGAlpha:(CGFloat)barBGAlpha {
    
    CustomNavBar *barbgView = (CustomNavBar *)self.navigationController.navigationBar;
    barbgView.barBGAlpha = barBGAlpha;
    
    objc_setAssociatedObject(self, &barBGAlphaKey, @(barBGAlpha), OBJC_ASSOCIATION_COPY_NONATOMIC);
}

- (CGFloat)barBGAlpha {
    
    return [objc_getAssociatedObject(self, &barBGAlphaKey) floatValue];
}

#pragma mark 配置tableview
- (void)setAutoRowHeight:(UITableView * _Nonnull)tableView {
    
    tableView.estimatedRowHeight = 44;
    tableView.rowHeight = UITableViewAutomaticDimension;
}
- (void)setAutoHeadHeight:(UITableView * _Nonnull)tableView {
    
    tableView.estimatedSectionHeaderHeight = 44;
    tableView.sectionHeaderHeight = UITableViewAutomaticDimension;
}
- (void)registCells:(NSArray * _Nonnull)nameArray tableView:(UITableView * _Nonnull)tableView {
    
    for (NSString *cellName in nameArray) {
        
        [tableView registerNib:[UINib nibWithNibName:cellName bundle:[NSBundle mainBundle]] forCellReuseIdentifier:cellName];
    }
}

#pragma mark - 分享

- (SnailSheetView *)sheetViewWithDelegate:(id<SnailSheetViewConfigDelegate>)delegate {
    
    SnailSheetView * sheet = [[SnailSheetView alloc] initWithFrame:CGRectMake(100, 100, kScreenWidth, 300) configDelegate:delegate];
    // sheet.headerLabel.text = @"IMGuider.com";
    
    sheet.models = [self sheetModels];
    [sheet autoresizingFlexibleHeight];
    
    
    return sheet;
}

- (void)popSheet {
    
    SnailSheetView * sheet = [self sheetViewWithDelegate:self];
    sheet.delegate = self;
    @weakify(self);
    sheet.didClickFooter = ^(SnailSheetView * _Nonnull sheetView) {
        @strongify(self);
        [self.sl_popupController dismiss];
    };
    
    
    self.sl_popupController = [SnailPopupController new];
    self.sl_popupController.layoutType = PopupLayoutTypeBottom;
    [self.sl_popupController presentContentView:sheet];
    
}


#pragma mark - SnailSheetViewConfig

- (SnailSheetViewLayout *)layoutOfItemInSheetView:(SnailSheetView *)sheetView {
    
    return [SnailSheetViewLayout layoutWithItemSize:CGSizeMake(kScreenWidth/4, 100)
                                      itemEdgeInset:UIEdgeInsetsMake(20, 0,0, 0)
                                        itemSpacing:0
                                     imageViewWidth:50
                                         subSpacing:10];
}


#define titleKey @"title"
#define imgNameKey @"imageName"
#define PlatformType @"platformType"

- (NSArray *)sheetModels {
    
    NSArray *arr1 = @[@{titleKey   : @"SHARE_WECHAT",
                        imgNameKey : @"微信",
                        PlatformType:@(UMSocialPlatformType_WechatSession)},
                      
                      @{titleKey   : @"SHARE_MOMENTS",
                        imgNameKey : @"朋友圈",
                        PlatformType:@(UMSocialPlatformType_WechatTimeLine)},
                      
                      @{titleKey   : @"SHARE_QQ",
                        imgNameKey : @"QQ",
                        PlatformType:@(UMSocialPlatformType_QQ)},
                      
                      @{titleKey   : @"SHARE_QZONE",
                        imgNameKey : @"QQ空间",
                        PlatformType:@(UMSocialPlatformType_Qzone)},
                      
                      @{titleKey   : @"SHARE_WEIBO",
                        imgNameKey : @"微博",
                        PlatformType:@(UMSocialPlatformType_Sina)},
                      
                      @{titleKey   : @"SHARE_FACEBOOK",
                        imgNameKey : @"Facebook",
                        PlatformType:@(UMSocialPlatformType_Facebook)}
                      ];
    
    //                      @{titleKey   : @"SHARE_TWITTER",
    //                        imgNameKey : @"Twitter",
    //                        PlatformType:@(UMSocialPlatformType_Twitter)}
    //                      ]
    
    NSMutableArray *array1 = [NSMutableArray array];
    for (NSDictionary *dict in arr1) {
        NSString *text = [dict objectForKey:titleKey];
        NSString *imgName = [dict objectForKey:imgNameKey];
        NSInteger type = ((NSNumber *)[dict objectForKey:PlatformType]).integerValue;
        if ([[UMSocialManager defaultManager] isInstall:type] || type == UMSocialPlatformType_Sina || type == UMSocialPlatformType_Facebook) {
            
            [array1 addObject:[SnailSheetItemModel modelWithText:text
                                                           image:[UIImage imageNamed:imgName] platformType:type]];
            
        }
        
    }
    
    NSMutableArray *array2 = [NSMutableArray array];
    
    if (array1.count > 4) {
        
        array2 =[NSMutableArray arrayWithArray:[array1 subarrayWithRange:NSMakeRange(4, array1.count - 4)]];
        [array1 removeObjectsInArray:array2];
    }
    
    return [NSMutableArray arrayWithObjects:array1, array2, nil];
}

- (void)sheetView:(nonnull SnailSheetView *)sheetView didSelectItemAtSection:(NSInteger)section index:(NSInteger)index {
    return;
}


@end


